<template>
  <div>
    <!-- 添加或修改资产清单表对话框 -->
    <el-dialog ref="editDialog" v-model="openFlag" :title="title" style="max-height: 86vh; width: 70vw;" append-to-body>
      <el-scrollbar always="true" max-height="60vh">
        <div class="ui_el_dialog_body">
          <el-form ref="form" :model="formData" :rules="rules" label-width="108px" class="dialog-form-two">
            <el-row>
              <el-text class="from-title-style">基本信息</el-text>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="资产名称" prop="name">
                  <el-input v-model.trim="formData.name" placeholder="请输入资产名称" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="资产编码" prop="number">
                  <el-input disabled v-model="formData.number" placeholder="自动生成" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="资产分类" prop="categoryId">
                  <category-select v-model="formData.categoryId"></category-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="8">
                <el-form-item label="品牌" prop="brand">
                  <el-input v-model.trim="formData.brand" placeholder="请输入品牌" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="型号" prop="model">
                  <el-input v-model.trim="formData.model" placeholder="请输入型号" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="计算单位" prop="unit">
                  <el-input v-model="formData.unit" placeholder="请输入计算单位"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="购置方式" prop="buyWay">
                  <el-select v-model="formData.buyWay" placeholder="请选择购置方式">
                    <el-option label="采购" value="procurement"></el-option>
                    <el-option label="租凭" value="rental"></el-option>
                    <el-option label="自建" value="self-built"></el-option>
                    <el-option label="捐赠" value="donation"></el-option>
                    <el-option label="其他" value="other"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="购置时间" prop="buyTime">
                  <date-editor v-model="formData.buyTime" placeholder="选择购置时间" :disabled="false">
                  </date-editor>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="购置金额" prop="buyPrice">
                  <el-input v-model.number="formData.buyPrice" placeholder="请输入购置金额" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="管理员" prop="adminId">
                  <user-select v-model.trim="formData.adminId" v-model:name="formData.adminName"
                    v-model:company-id="formData.companyId" v-model:company-name="formData.companyName"
                    placeholder="请选择管理员"></user-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="所在公司" prop="company">
                  <el-input v-model.number="formData.companyName" placeholder="请输入所在公司" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="所在仓库" prop="warehouseId">
                  <warehouse-select v-model="formData.warehouseId"></warehouse-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="位置" prop="location">
                  <el-input v-model.number="formData.location" placeholder="请输入使用位置" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="使用人" prop="User">
                  <user-select v-model="formData.userId" v-model:name="formData.userName" v-model:dept-name="formData.deptName">
                    placeholder="请选择使用人"></user-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="使用部门" prop="department">
                  <el-input v-model="formData.deptName" placeholder="请输入使用部门" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="使用期限(月)" prop="location">
                  <el-input v-model.number="formData.serviceLife" placeholder="请输入使用期限" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="领用时间" prop="Checkout">
                  <date-editor v-model="formData.useTime" placeholder="领用时间" :disabled="false">
                  </date-editor>
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="图片" prop="imgUrl">
                  <el-upload class="avatar-uploader" :headers="headersObj" :action="uploadUrl" :show-file-list="false"
                    :on-success="handleUploadSuccess" :before-upload="beforeUpload">
                    <img alt="" v-if="formData.imgUrl" :src="imgUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                      <Plus />
                    </el-icon>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-text class="from-title-style">维保信息</el-text>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="供应商">
                  <el-input v-model.trim="formData.supplier" placeholder="请输入供应商" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="供应商联系人">
                  <el-input v-model.trim="formData.supplierContact" placeholder="请输入供应商联系人" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="联系电话">
                  <el-input v-model.trim="formData.contactPhone" placeholder="请输入联系电话" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="负责人">
                  <user-select v-model="formData.maintenanceUserId"
                    v-model:name="formData.maintenanceUserName"></user-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="保养到期时间">
                  <date-editor v-model="formData.deadlineTime" type="date" size="default" placeholder="请选择保养到期时间" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="折旧期限(月)" prop="depreciation">
                  <el-input v-model.trim="formData.depreciation" placeholder="请输入折旧期限" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="保养说明" prop="maintenanceDescription">
                  <el-input v-model="formData.maintenanceDescription" type="textarea" :rows="5" placeholder="请输入保养说明" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-scrollbar>
      <template #footer>
        <div class="ui_el_dialog_footer">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" style="color: #fff; background-color: #005bf5;" @click="submitForm">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <choose-category :form="formData" ref="chooseCategoryDialog"></choose-category>
  </div>
</template>

<script setup>

import { addAssetItem, updateAssetItem, getAssetItem } from "@/api/asset/assetItem";
import ChooseCategory from './chooseCategory.vue'
import UserSelect from "@/components/User/UserSelect.vue";
import CategorySelect from "@/components/Asset/CategorySelect.vue";
import WarehouseSelect from "@/components/Warehouse/WarehouseSelect.vue";

import { getToken } from '@/utils/auth'
import DateEditor from "@/components/Common/DateEditor.vue";

const { proxy } = getCurrentInstance();

const emit = defineEmits(["sub"]);
const chooseCategoryDialog = ref();
const form = ref();

const openFlag = ref(false)
const initFormData = {
  id: null,
  number: null,
  name: null,
  categoryId: null,
  categoryName: null,
  rfid: null,
  brand: null,
  model: null,
  buyWay: null,
  buyTime: null,
  buyPrice: null,
  unit: null,
  adminId: null,
  imgUrl: null,
  depreciation: null,
  warehouseId: null,
  serviceLife: null,
  location: null
}

const formData = reactive({});
const uploadUrl = import.meta.env.VITE_APP_BASE_API + '/uploadImg';

const rules = {
  name: [
    { required: true, message: "资产名称不能为空", trigger: "blur" }
  ],

  adminId: [
    { required: true, message: "管理员不能为空", trigger: "blur" }
  ],
  categoryId: [
    { required: true, message: "资产分类不能为空", trigger: "change" }
  ],
  imgUrl: [
    { required: true, message: "请上传资产图片", trigger: "blur" }
  ],
  warehouseId: [
    { required: true, message: "所在仓库不能为空", trigger: "change" }
  ]
}

let isEdit = ref(false);
let title = computed(() => isEdit.value ? '编辑' : '添加资产');
const headersObj = {
  'Authorization': 'Bearer ' + getToken()
}

const imgUrl = computed(() => {
  return import.meta.env.VITE_APP_BASE_API + formData.imgUrl;
});

/**
 * 重置
 */
function reset() {
  Object.assign(formData, initFormData);
}

function open(row) {
  reset();
  openFlag.value = true;
  if (row) {
    isEdit.value = true;
    handleUpdate(row);
  } else {
    isEdit.value = false;
  }
}

function close() {
  openFlag.value = false;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  const id = row.id;
  getAssetItem(id).then(response => {
    Object.assign(formData, response);
  });
}

function beforeUpload(rawFile) {

  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    proxy.$modal.alert('请上传图片格式!');
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    proxy.$modal.alert('图片不能超过2M!');
    return false
  }
  return true
}

function handleUploadSuccess(response) {
  formData.imgUrl = response.fileName;
}

function check() {
  return new Promise((_, reject) => {
    form.value.validate(valid => {
      _(valid);
    });
  });

}

/** 提交按钮 */
async function submitForm() {
  const valid = await check();
  if (!valid) {
    return proxy.$modal.alert("校验失败，请检查无效的输入项");
  }
  if (isEdit.value) {
    updateAssetItem(formData).then(response => {
      proxy.$modal.msgSuccess("修改成功");
      openFlag.value = false;
      emit("sub");
    });
  } else {
    addAssetItem(formData).then(response => {
      proxy.$modal.msgSuccess("新增成功");
      openFlag.value = false;
      emit("sub");
    })
  }
}

defineExpose({
  open
})

</script>

<style scoped lang="scss">
dialog-form-two {
  display: flex;
}

.avatar-uploader {
  width: 180px;
  height: 80px;
  background-color: #fff;
  border-radius: 2px;
  border: 1px dashed #d9dbde;
  flex-shrink: 0;
  overflow: hidden;
  cursor: pointer;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 180px;
  height: 80px;
  text-align: center;
}

.avatar {
  width: 80px;
  height: 80px;
}
</style>